#!/bin/bash

# 基本路径
TOMCAT_PATH="/home/linux_7230263146/tomcat9"
EXAM_PATH="/home/linux_7230263146/Exam"
TARGET_PATH="$EXAM_PATH/target"
FRONTEND_PATH="$EXAM_PATH/WebExam"



# 构建classpath
CP="${TOMCAT_PATH}/lib/servlet-api.jar"

# 加入 gson.jar
GSON_JAR="$EXAM_PATH/code/lib/gson-2.10.1.jar"
CP="$CP:$GSON_JAR"


# 步骤1：准备CP变量
for jar in "$TOMCAT_PATH/webapps/ROOT/WEB-INF/lib/"*.jar; do
  CP="$CP:$jar"
done

# 步骤2：编译
echo ">>> 开始编译..."

# 创建输出目录
mkdir -p "$TARGET_PATH/classes"

# 编译
javac -encoding UTF-8 -cp "$CP" -d "$TARGET_PATH/classes" "$EXAM_PATH/code/"*.java

if [ $? -ne 0 ]; then
  echo ">>> 编译失败，请检查代码。"
  exit 1
else
  echo ">>>✅编译成功"
fi

# 步骤3：部署
# 拷贝 class 文件到 Tomcat
echo ">>> 部署 class 文件..."
mkdir -p "$TOMCAT_PATH/webapps/ROOT/WEB-INF/classes"
cp -r "$TARGET_PATH/classes/"* "$TOMCAT_PATH/webapps/ROOT/WEB-INF/classes/"


# 拷贝 gson.jar到 WEB-INF/lib
mkdir -p "$TOMCAT_PATH/webapps/ROOT/WEB-INF/lib"
cp "$GSON_JAR" "$TOMCAT_PATH/webapps/ROOT/WEB-INF/lib/"

# 拷贝前端页面
echo ">>> 部署前端页面..."
cp -r "$FRONTEND_PATH/"* "$TOMCAT_PATH/webapps/ROOT/"


#步骤4：重启
echo ">>> 重启 Tomcat..."
PID=$(ps aux | grep "$TOMCAT_PATH" | grep -v grep | awk '{print $2}')
if [ -n "$PID" ]; then
  kill -9 "$PID"
  sleep 2
fi
"$TOMCAT_PATH/bin/startup.sh"

echo ">>> 项目部署完成，请访问：http://47.110.252.237"

